{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Hikyuu 交互式工具示例\n",
    "=============="
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1、引入交互式工具\n",
    "-----------------\n",
    "需从hikyuu.interactive引入，而不是直接从hikyuu库中引入（hikyuu是一个库，可用于编制其他的工具，而hikyuu.interactive是基于hikyuu库实现的交互式探索工具）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 127 μs, sys: 183 μs, total: 310 μs\n",
      "Wall time: 312 μs\n"
     ]
    }
   ],
   "source": [
    "%matplotlib inline\n",
    "%time from hikyuu.interactive import *\n",
    "#use_draw_engine('echarts') #use_draw_engine('matplotlib')  #默认为'matplotlib'绘图"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2、创建交易系统并运行\n",
    "--------------------"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "#创建模拟交易账户进行回测，初始资金30万\n",
    "my_tm = crtTM(init_cash = 300000)\n",
    "\n",
    "#创建信号指示器（以5日EMA为快线，5日EMA自身的10日EMA作为慢线，快线向上穿越慢线时买入，反之卖出）\n",
    "my_sg = SG_Flex(EMA(C, n=5), slow_n=10)\n",
    "\n",
    "#固定每次买入1000股\n",
    "my_mm = MM_FixedCount(1000)\n",
    "\n",
    "#创建交易系统并运行\n",
    "sys = SYS_Simple(tm = my_tm, sg = my_sg, mm = my_mm)\n",
    "sys.run(sm['sz000001'], Query(-150))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "3、绘制曲线观察\n",
    "---------------"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "#绘制系统信号\n",
    "sys.plot()\n",
    "\n",
    "k = sm['sz000001'].get_kdata(Query(-150))\n",
    "c = CLOSE(k)\n",
    "fast = EMA(c, 5)\n",
    "slow = EMA(fast, 10)\n",
    "\n",
    "#绘制信号指示器使用两个指标\n",
    "fast.plot(new=False)\n",
    "slow.plot(new=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "4、绘制资金收益曲线\n",
    "---------------------"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "#绘制资金收益曲线\n",
    "x = my_tm.get_profit_curve(k.get_datetime_list(), Query.DAY)\n",
    "x = PRICELIST(x)\n",
    "x.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "5、回测统计报告\n",
    "----------------------"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "帐户初始金额: 300000.00\n",
      "累计投入本金: 300000.00\n",
      "累计投入资产: 0.00\n",
      "累计借入现金: 0.00\n",
      "累计借入资产: 0.00\n",
      "累计红利: 0.00\n",
      "现金余额: 287880.00\n",
      "未平仓头寸净值: 11460.00\n",
      "当前总资产: 299340.00\n",
      "已平仓交易总成本: 0.00\n",
      "已平仓净利润总额: -1050.00\n",
      "单笔交易最大占用现金比例%: 3.98\n",
      "交易平均占用现金比例%: 3.84\n",
      "已平仓帐户收益率%: -0.35\n",
      "帐户年复合收益率%: -0.39\n",
      "帐户平均年收益率%: -0.39\n",
      "赢利交易赢利总额: 130.00\n",
      "亏损交易亏损总额: -1180.00\n",
      "已平仓交易总数: 7.00\n",
      "赢利交易数: 1.00\n",
      "亏损交易数: 6.00\n",
      "赢利交易比例%: 14.29\n",
      "赢利期望值: -150.00\n",
      "赢利交易平均赢利: 130.00\n",
      "亏损交易平均亏损: -196.67\n",
      "平均赢利/平均亏损比例: 0.66\n",
      "净赢利/亏损比例: 0.11\n",
      "最大单笔赢利: 130.00\n",
      "最大单笔盈利百分比%: 1.14\n",
      "最大单笔亏损: -470.00\n",
      "最大单笔亏损百分比%: -4.00\n",
      "赢利交易平均持仓时间: 16.00\n",
      "赢利交易最大持仓时间: 16.00\n",
      "亏损交易平均持仓时间: 9.67\n",
      "亏损交易最大持仓时间: 28.00\n",
      "空仓总时间: 130.00\n",
      "空仓时间/总时间%: 63.00\n",
      "平均空仓时间: 18.00\n",
      "最长空仓时间: 38.00\n",
      "最大连续赢利笔数: 1.00\n",
      "最大连续亏损笔数: 3.00\n",
      "最大连续赢利金额: 130.00\n",
      "最大连续亏损金额: -910.00\n",
      "R乘数期望值: -0.01\n",
      "交易机会频率/年: 12.52\n",
      "年度期望R乘数: -0.13\n",
      "赢利交易平均R乘数: 0.01\n",
      "亏损交易平均R乘数: -0.02\n",
      "最大单笔赢利R乘数: 0.01\n",
      "最大单笔亏损R乘数: -0.04\n",
      "最大连续赢利R乘数: 0.01\n",
      "最大连续亏损R乘数: -0.03\n",
      "最大回撤百分比: -0.28\n",
      "夏普比率: -1.59\n",
      "单笔交易盈亏百分比均值: -1.27\n",
      "单笔交易盈亏百分比标准差: 1.96\n",
      "\n"
     ]
    }
   ],
   "source": [
    "#回测统计\n",
    "from datetime import datetime\n",
    "\n",
    "per = my_tm.get_performance()\n",
    "print(per.report())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "6、关于性能\n",
    "---------------\n",
    "\n",
    "经常有人问到性能问题，下面这段的代码使用之前的系统示例，遍历指定板块的所有股票，计算他们的“盈利交易比例%”（即胜率）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "def test_func(stock, query):\n",
    "    \"\"\"计算指定stock的系统策略胜率，系统策略为之前的简单双均线交叉系统（每次固定买入100股）\n",
    "    \"\"\"\n",
    "    #创建模拟交易账户进行回测，初始资金30万\n",
    "    my_tm = crtTM(init_cash = 1000000)\n",
    "\n",
    "    #创建信号指示器（以5日EMA为快线，5日EMA自身的10日EMA作为慢线，快线向上穿越慢线时买入，反之卖出）\n",
    "    my_sg = SG_Flex(EMA(C, n=5), slow_n=10)\n",
    "\n",
    "    #固定每次买入1000股\n",
    "    my_mm = MM_FixedCount(100)\n",
    "\n",
    "    #创建交易系统并运行\n",
    "    sys = SYS_Simple(tm = my_tm, sg = my_sg, mm = my_mm)\n",
    "    sys.run(stock, query)\n",
    "    \n",
    "    per = Performance()\n",
    "    per.statistics(my_tm, Datetime(datetime.today()))\n",
    "    return per[\"赢利交易比例%\".encode('gb2312')]\n",
    "\n",
    "def total_func(blk, query):\n",
    "    \"\"\"遍历指定板块的所有的股票，计算系统胜率\"\"\"\n",
    "    result = {}\n",
    "    for s in blk:\n",
    "        if s.valid and s.type != constant.STOCKTYPE_INDEX:\n",
    "            result[s.name] = test_func(s, query)\n",
    "    return result"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "遍历所有当前有效且并非指数的证券。下面是我的机器执行结果，共计算4151支证券，最近500个交易日，共耗时2.89秒。机器配置：Intel i7-4700HQ 2.G。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 1.51 s, sys: 76.2 ms, total: 1.59 s\n",
      "Wall time: 1.12 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "6790"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%time a = total_func(sm, Query(-500))\n",
    "len(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
